/*
 * @Author: 2112778581 2112778581@qq.com
 * @Date: 2023-10-16 13:41:36
 * @LastEditors: fengshan525 2735332396@qq.com
 * @LastEditTime: 2025-09-21 16:56:06
 * @FilePath: \pra\src\list-detail\list-detail.controller.ts
 * @Description: 列表详情控制器
 */
import { ListDetail } from '@libs/db/models/list-detail.model';
import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Public } from 'src/decorations/public.decorator';
import { Category } from '@libs/db/models/category.model';
import { WebmenusService } from '../webmenus/webmenus.service';
import { ListDetailService } from './list-detail.service';

@Controller('list-detail')
export class ListDetailController {
  constructor(
    @InjectModel('ListDetail') private readonly listDetailModel: Model<ListDetail>,
    @InjectModel('Category') private readonly categoryModel: Model<Category>,
    private readonly webmenusService: WebmenusService,
    private readonly listDetailService: ListDetailService
  ) { }

  /**
   * 创建列表详情
   * @param createListDetailDto 创建列表详情的数据传输对象
   * @returns 创建的列表详情对象
   */
  @Post()
  @Public()
  async create(@Body() createListDetailDto: ListDetail) {
    const doc = await this.listDetailModel.create(createListDetailDto);
    const res = await doc.save();
    return res;
  }

  /**
   * 分页查询所有列表详情
   * @param body 查询参数，包含分页信息和分类ID（可能是父节点ID）
   * @returns 分页查询结果
   */
  @Post('/findAll')
  @Public()
  async findAll(@Body() body: any) {
    try {
      return await this.listDetailService.findAllWithFilters(body);
    } catch (error) {
      throw new HttpException('查询失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }


  @Post('/getCategoryCount')
  @Public()
  async getCategoryCount(@Body() body: any) {
    try {
      return await this.listDetailService.findAllWithFiltersCount(body);
    } catch (error) {
      throw new HttpException('查询失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Post('/findPublished')
  @Public()
  async findPublished(@Body() body: any) {
    try {
      return await this.listDetailService.findAllWithRecommendSort(body);
    } catch (error) {
      throw new HttpException('查询失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 获取下拉列表数据
   * @returns 下拉列表数据
   */
  @Post('getDropdownList')
  async getDropdownList() {
    try {
      const data = await this.listDetailModel
        .find({ isPublished: true })
        .select('title _id')
        .sort({ createdAt: -1 });
      return {
        code: 200,
        data,
        message: '获取成功',
      };
    } catch (error) {
      return {
        code: 500,
        message: '获取失败',
      };
    }
  }

  /**
   * 根据单个分类查询列表详情
   * @param body 查询参数，包含分类ID和分页信息
   * @returns 查询结果
   */
  @Post('/findByOption')
  @Public()
  async findAllByOption(@Body() body: any) {
    try {
      const { categoryId, pageNum = 1, pageSize = 10 } = body;
      const skip = (pageNum - 1) * pageSize;

      const total = await this.listDetailModel.countDocuments({
        categoryId,
      });
      const data = await this.listDetailModel
        .find({ categoryId })
        .skip(skip)
        .limit(parseInt(pageSize))
        .sort({ createdAt: -1 });

      return {
        data,
        total,
        pageNum: parseInt(pageNum),
        pageSize: parseInt(pageSize),
      };
    } catch (error) {
      return {
        code: 500,
        message: '查询失败',
      };
    }
  }

  /**
   * 根据分类查询列表详情
   * @param body 查询参数
   * @returns 查询结果
   */
  @Post('/findByCate')
  @Public()
  async findAllByCategory(@Body() body: any) {
    try {
      const { categoryIds, pageNum = 1, pageSize = 10 } = body;
      const skip = (pageNum - 1) * pageSize;

      const data = await this.listDetailModel
        .find({
          categoryId: { $in: categoryIds },
          isPublished: true
        })
        .skip(skip)
        .limit(parseInt(pageSize))
        .sort({ createdAt: -1 });

      return { data };
    } catch (error) {
      throw new HttpException('查询失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 根据ID获取单个列表详情
   * @param id 列表详情ID（来源：用户输入）
   * @returns 列表详情对象
   */
  @Get('/getById/:id')
  @Public()
  async findOne(@Param('id') id: string) {
    try {
      return await this.listDetailModel.findById(id);
    } catch (error) {
      throw new HttpException('查询失败', HttpStatus.NOT_FOUND);
    }
  }

  /**
   * 根据ID获取单个列表详情
   * @param id 列表详情ID（来源：用户输入）
   * @returns 列表详情对象
   */
  @Get('/getDetailByLinkName/:linkName')
  @Public()
  async getDetailByLinkName(@Param('linkName') linkName: string) {
    try {
      // 增加浏览量
      await this.listDetailModel.findOneAndUpdate({ linkName }, { $inc: { viewCount: 1 } });
      return await this.listDetailModel.findOne({ linkName });
    } catch (error) {
      throw new HttpException('查询失败', HttpStatus.NOT_FOUND);
    }
  }

  /**
   * 根据modelId查询列表详情
   * @param modelId 模型ID（来源：用户输入）
   * @returns 列表详情数组
   */
  @Get('/getByModelId/:modelId')
  @Public()
  async findByModelId(@Param('modelId') modelId: string) {
    try {
      return await this.listDetailModel
        .find({ modelId, isPublished: true })
        .sort({ createdAt: -1 });
    } catch (error) {
      throw new HttpException('根据modelId查询失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 根据标题搜索列表详情
   * @param body 搜索参数
   * @returns 搜索结果
   */
  @Post('/list/search')
  @Public()
  async findByName(@Body() body: any) {
    try {
      const { keyword, pageNum = 1, pageSize = 10 } = body;
      const skip = (pageNum - 1) * pageSize;

      const query = {
        $or: [
          { title: { $regex: keyword, $options: 'i' } },
          { description: { $regex: keyword, $options: 'i' } },
          { content: { $regex: keyword, $options: 'i' } }
        ],
        isPublished: true
      };

      const total = await this.listDetailModel.countDocuments(query);
      const data = await this.listDetailModel
        .find(query)
        .skip(skip)
        .limit(parseInt(pageSize))
        .sort({ createdAt: -1 });

      return {
        data,
        total,
        pageNum: parseInt(pageNum),
        pageSize: parseInt(pageSize),
      };
    } catch (error) {
      throw new HttpException('搜索失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 更新列表详情
   * @param id 列表详情ID
   * @param updateListDetailDto 更新数据
   * @returns 更新结果
   */
  @Post('/update/:id')
  @Public()
  async update(@Param('id') id: string, @Body() updateListDetailDto: any) {
    return await this.listDetailModel.findByIdAndUpdate(id, updateListDetailDto, {
      new: true,
    });
  }

  /**
   * 删除列表详情
   * @param id 列表详情ID
   * @returns 删除结果
   */
  @Delete(':id')
  @Public()
  async remove(@Param('id') id: string) {
    try {
      const result = await this.listDetailModel.findByIdAndDelete(id);
      if (!result) {
        throw new HttpException('列表详情不存在', HttpStatus.NOT_FOUND);
      }
      return { message: '删除成功' };
    } catch (error) {
      throw new HttpException('删除失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}

